#include "fileio.h"
#include "employee.h"
#include <stdio.h>

#define FILENAME "data.txt"

void savetofile() {
    FILE *file = fopen(FILENAME, "w");
    if (file == NULL) {
        printf("打开文件失败！\n");
        return;
    }

    for (int i = 0; i < current_employee_count; i++) {
        fprintf(file, "%d %s %f %f %f\n",
                employees[i].id, employees[i].name, employees[i].base_salary, employees[i].bonus, employees[i].total_salary);
    }

    fclose(file);
    printf("数据已成功保存到 %s\n", FILENAME);
}

void loadfromfile() {
    FILE *file = fopen(FILENAME, "r");
    if (file == NULL) {
        printf("打开文件失败！可能数据文件不存在。\n");
        return;
    }

    current_employee_count = 0;  // 重置员工数量

    while (fscanf(file, "%d %s %f %f %f", &employees[current_employee_count].id, employees[current_employee_count].name,
                  &employees[current_employee_count].base_salary, &employees[current_employee_count].bonus, &employees[current_employee_count].total_salary) != EOF) {
        current_employee_count++;
    }

    fclose(file);
    printf("数据已从 %s 中加载。\n", FILENAME);
}
